#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
金投网实时金价获取器
专门从 https://quote.cngold.org/gjs/swhj_zghj.html 获取中国黄金实时价格
"""

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
import re
import time


def get_cngold_realtime_price() -> tuple:
    """
    从金投网获取中国黄金实时价格
    URL: https://quote.cngold.org/gjs/swhj_zghj.html
    
    Returns:
        tuple: (金价(元/克), 获取时间字符串, 数据来源)
    """
    url = "https://quote.cngold.org/gjs/swhj_zghj.html"
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1'
    }
    
    try:
        print(f"正在从金投网获取实时金价...")
        print(f"数据源: {url}")
        
        # 配置Chrome选项
        chrome_options = Options()
        chrome_options.add_argument("--headless")  # 无头模式
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--disable-web-security")
        chrome_options.add_argument("--disable-features=VizDisplayCompositor")
        chrome_options.add_argument("--window-size=1920,1080")
        chrome_options.add_argument(f"--user-agent={headers['User-Agent']}")
        
        # 初始化WebDriver
        try:
            from webdriver_manager.chrome import ChromeDriverManager
            driver = webdriver.Chrome(
                service=webdriver.chrome.service.Service(ChromeDriverManager().install()),
                options=chrome_options
            )
        except:
            driver = webdriver.Chrome(options=chrome_options)
        
        try:
            # 访问页面
            driver.get(url)
            
            # 等待页面加载
            wait = WebDriverWait(driver, 15)
            time.sleep(3)  # 额外等待确保页面完全加载
            
            # 查找中国黄金价格相关的元素
            price_found = False
            current_price = None
            
            # 方法1: 查找表格中的价格数据
            try:
                # 查找包含价格的表格行
                table_rows = driver.find_elements(By.CSS_SELECTOR, "table tr")
                for row in table_rows:
                    cells = row.find_elements(By.TAG_NAME, "td")
                    if len(cells) >= 2:
                        for cell in cells:
                            text = cell.text.strip()
                            # 查找价格模式 (xxx.xx 格式)
                            price_match = re.search(r'(\d{3,4}\.\d{1,2})', text)
                            if price_match:
                                potential_price = float(price_match.group(1))
                                # 验证价格在合理范围内 (400-800元/克)
                                if 400 <= potential_price <= 800:
                                    current_price = potential_price
                                    price_found = True
                                    print(f"从表格中找到价格: {current_price} 元/克")
                                    break
                    if price_found:
                        break
            except Exception as e:
                print(f"表格解析失败: {e}")
            
            # 方法2: 查找特定的价格显示元素
            if not price_found:
                try:
                    price_selectors = [
                        ".price",
                        ".current-price",
                        ".gold-price",
                        "[data-price]",
                        ".quote-price",
                        ".real-price",
                        ".market-price"
                    ]
                    
                    for selector in price_selectors:
                        try:
                            elements = driver.find_elements(By.CSS_SELECTOR, selector)
                            for element in elements:
                                text = element.text.strip()
                                price_match = re.search(r'(\d{3,4}\.\d{1,2})', text)
                                if price_match:
                                    potential_price = float(price_match.group(1))
                                    if 400 <= potential_price <= 800:
                                        current_price = potential_price
                                        price_found = True
                                        print(f"从选择器 {selector} 找到价格: {current_price} 元/克")
                                        break
                            if price_found:
                                break
                        except:
                            continue
                except Exception as e:
                    print(f"选择器解析失败: {e}")
            
            # 方法3: 全页面搜索包含价格的元素
            if not price_found:
                try:
                    all_elements = driver.find_elements(By.XPATH, "//*[contains(text(), '.')]")
                    for element in all_elements:
                        try:
                            text = element.text.strip()
                            if text and len(text) < 20:  # 避免长文本
                                # 查找价格模式
                                price_matches = re.findall(r'(\d{3,4}\.\d{1,2})', text)
                                for match in price_matches:
                                    potential_price = float(match)
                                    if 400 <= potential_price <= 800:
                                        current_price = potential_price
                                        price_found = True
                                        print(f"从全页面搜索找到价格: {current_price} 元/克")
                                        break
                                if price_found:
                                    break
                        except:
                            continue
                except Exception as e:
                    print(f"全页面搜索失败: {e}")
            
            # 如果找到了价格
            if price_found and current_price:
                current_time = datetime.now()
                time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
                
                print(f"✅ 成功获取金投网实时金价: {current_price} 元/克")
                print(f"⏰ 获取时间: {time_str}")
                
                return (current_price, time_str, "金投网")
            else:
                print("❌ 未能在页面中找到有效的金价数据")
                return (0.0, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "金投网(解析失败)")
                
        finally:
            driver.quit()
            
    except Exception as e:
        print(f"❌ 获取金投网金价时出错: {e}")
        current_time = datetime.now()
        return (0.0, current_time.strftime("%Y-%m-%d %H:%M:%S"), "金投网(连接失败)")


def test_gold_price_fetcher():
    """测试金价获取功能"""
    print("🚀 开始测试金投网实时金价获取...")
    
    try:
        price, time_str, source = get_cngold_realtime_price()
        
        print(f"\n📊 测试结果:")
        print(f"金价: {price} 元/克")
        print(f"时间: {time_str}")
        print(f"来源: {source}")
        
        if price > 0:
            print("✅ 测试成功！")
            
            # 计算其他单位的价格
            ounce_price = price * 31.1035  # 1盎司 ≈ 31.1035克
            ten_gram_price = price * 10
            
            print(f"\n💰 价格换算:")
            print(f"1盎司黄金: {ounce_price:.2f} 元")
            print(f"10克黄金: {ten_gram_price:.2f} 元")
        else:
            print("❌ 测试失败，未获取到有效价格")
            
    except Exception as e:
        print(f"❌ 测试过程中出错: {e}")


if __name__ == "__main__":
    test_gold_price_fetcher() 